// DemoDlg.cpp : implementation file
//

#include "stdafx.h"
#include "Demo.h"
#include "DemoDlg.h"
#include "UHFApiV10.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

int nTransMode = 1;//TCP:nTransMode = 0 ;  SerialPort:nTransMode = 1 .

char CommPort[20][6] = {"COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","COM10",
						"COM11","COM12","COM13","COM14","COM15","COM16","COM17","COM18","COM19","COM20"};
HANDLE hComHandle;
unsigned char ReaderAddr;
TagIds IdBuf[300];
int IsoReadCnt,EpcReadCnt;
int ReadSucessCnt;
int MultiTagCnt;
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam);
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDemoDlg dialog

CDemoDlg::CDemoDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CDemoDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CDemoDlg)
	m_EpcData = _T("");
	m_IsoData = _T("");
	m_password = _T("");
	m_Check6B = FALSE;
	m_CheckEPC = FALSE;
	m_LocalPort = _T("");
	m_Ant1 = FALSE;
	m_Ant2 = FALSE;
	m_Ant3 = FALSE;
	m_Ant4 = FALSE;
	m_Ant5 = FALSE;
	m_Ant6 = FALSE;
	m_Ant7 = FALSE;
	m_Ant8 = FALSE;
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CDemoDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CDemoDlg)
	DDX_Control(pDX, IDC_BTN_SETOUT, m_Setout_Btn);
	DDX_Control(pDX, COMBO_POWER, m_PowerSet);
	DDX_Control(pDX, COMBO_FERQICT, m_Freq);
	DDX_Control(pDX, IDC_IP, m_LocalIP);
	DDX_Control(pDX, COMBO_ISO_CNT, m_E_IsoCnt);
	DDX_Control(pDX, COMBO_ISO_ADDR, m_E_IsoAddr);
	DDX_Control(pDX, COMBO_6B_SELECT, m_SelectISO);
	DDX_Control(pDX, COMBO_EPC_SELECT, m_SelectEPC);
	DDX_Control(pDX, IDC_EPC_KILL, m_EpcKill);
	DDX_Control(pDX, BUTTON_INIT, m_B_EpcInit);
	DDX_Control(pDX, EDIT_EPC_DATA, m_E_EpcData);
	DDX_Control(pDX, EDIT_ISO_DATA, m_E_IsoData);
	DDX_Control(pDX, LIST_INFO, m_ListData);
	DDX_Control(pDX, COMBO_ISO_INTERVAL, m_C_IsoInterval);
	DDX_Control(pDX, COMBO_EPC_WORDPTR, m_C_EpcWordPtr);
	DDX_Control(pDX, COMBO_EPC_WORDCNT, m_C_EpcWordCnt);
	DDX_Control(pDX, COMBO_EPC_TIEMS, m_C_EpcTimes);
	DDX_Control(pDX, COMBO_EPC_MEMBANK, m_C_EpcMembank);
	DDX_Control(pDX, COMBO_EPC_INTERVAL, m_C_EpcInterval);
	DDX_Control(pDX, COMBO_PORT, m_C_Port);
	DDX_Control(pDX, COMBO_ISO_TIMES, m_C_IsoTimes);
	DDX_Control(pDX, COMBO_BAUDRATE, m_C_Baudrate);
	DDX_Control(pDX, COMBO__READER_ADDR, m_C_ReadAddr);
	DDX_Control(pDX, BUTTON_ISO_WRITE, m_B_IsoWrite);
	DDX_Control(pDX, BUTTON_ISO_STOP, m_B_IsoStop);
	DDX_Control(pDX, BUTTON_ISO_READ, m_B_IsoRead);
	DDX_Control(pDX, BUTTON_ISO_QUERY, m_B_IsoQuery);
	DDX_Control(pDX, BUTTON_ISO_LOCK, m_B_IsoLock);
	DDX_Control(pDX, BUTTON_ISO_ID, m_B_IsoId);
	DDX_Control(pDX, BUTTON_EPC_WRITE, m_B_EpcWrite);
	DDX_Control(pDX, BUTTON_EPC_STOP, m_B_EpcStop);
	DDX_Control(pDX, BUTTON_EPC_READ, m_B_EpcRead);
	DDX_Control(pDX, BUTTON_EPC_LOCK, m_B_EpcLock);
	DDX_Control(pDX, BUTTON_EPC_ID, m_B_EpcId);
	DDX_Control(pDX, BUTTON_DISCON, m_B_Discon);
	DDX_Control(pDX, BUTTON_CON, m_B_Con);
	DDX_Control(pDX, BUTTON_CLEAR, m_B_Clear);
	DDX_Text(pDX, EDIT_EPC_DATA, m_EpcData);
	DDX_Text(pDX, EDIT_ISO_DATA, m_IsoData);
	DDX_Text(pDX, IDC_KILL_PASSWORD, m_password);
	DDV_MaxChars(pDX, m_password, 8);
	DDX_Check(pDX, IDC_CHECK_6B, m_Check6B);
	DDX_Check(pDX, IDC_CHECK_EPC, m_CheckEPC);
	DDX_Text(pDX, IDC_PORT, m_LocalPort);
	DDX_Check(pDX, IDC_CHECK_ANT1, m_Ant1);
	DDX_Check(pDX, IDC_CHECK_ANT2, m_Ant2);
	DDX_Check(pDX, IDC_CHECK_ANT3, m_Ant3);
	DDX_Check(pDX, IDC_CHECK_ANT4, m_Ant4);
	DDX_Check(pDX, IDC_CHECK_ANT5, m_Ant5);
	DDX_Check(pDX, IDC_CHECK_ANT6, m_Ant6);
	DDX_Check(pDX, IDC_CHECK_ANT7, m_Ant7);
	DDX_Check(pDX, IDC_CHECK_ANT8, m_Ant8);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CDemoDlg, CDialog)
	//{{AFX_MSG_MAP(CDemoDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(BUTTON_CON, OnCon)
	ON_BN_CLICKED(BUTTON_DISCON, OnDiscon)
	ON_WM_CLOSE()
	ON_WM_TIMER()
	ON_BN_CLICKED(BUTTON_ISO_ID, OnIsoId)
	ON_BN_CLICKED(BUTTON_ISO_STOP, OnIsoStop)
	ON_BN_CLICKED(BUTTON_CLEAR, OnClear)
	ON_EN_CHANGE(EDIT_POWER, OnChangePower)
	ON_BN_CLICKED(BUTTON_ISO_READ, OnIsoRead)
	ON_EN_CHANGE(EDIT_ISO_ADDR, OnChangeIsoAddr)
	ON_EN_CHANGE(EDIT_ISO_CNT, OnChangeIsoCnt)
	ON_BN_CLICKED(BUTTON_ISO_WRITE, OnIsoWrite)
	ON_BN_CLICKED(BUTTON_ISO_LOCK, OnIsoLock)
	ON_BN_CLICKED(BUTTON_ISO_QUERY, OnIsoQuery)
	ON_BN_CLICKED(BUTTON_EPC_ID, OnEpcId)
	ON_BN_CLICKED(BUTTON_EPC_STOP, OnEpcStop)
	ON_BN_CLICKED(BUTTON_EPC_READ, OnEpcRead)
	ON_BN_CLICKED(BUTTON_INIT, OnInit)
	ON_BN_CLICKED(BUTTON_EPC_WRITE, OnEpcWrite)
	ON_BN_CLICKED(BUTTON_EPC_LOCK, OnEpcLock)
	ON_BN_CLICKED(IDC_EPC_KILL, OnEpcKill)
	ON_BN_CLICKED(BUTTON_SAVELOG, OnSavelog)
	ON_BN_CLICKED(IDC_RADIO1, OnRadio1)
	ON_BN_CLICKED(IDC_RADIO2, OnRadio2)
	ON_BN_CLICKED(IDC_BTN_QUERY, OnBtnQuery)
	ON_BN_CLICKED(IDC_BTN_SETTING, OnBtnSetting)
	ON_BN_CLICKED(IDC_BTN_SETOUT, OnBtnSetout)
	ON_BN_CLICKED(IDC_BTN_RESET, OnBtnReset)
	ON_BN_CLICKED(BUTTON_EPC_FASTWRITE, OnEpcFastwrite)
	ON_BN_CLICKED(IDC_BTN_GETANT, OnBtnGetant)
	ON_BN_CLICKED(IDC_BTN_SETANT, OnBtnSetant)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDemoDlg message handlers

BOOL CDemoDlg::OnInitDialog()
{
	int i;
	CString s;
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	m_LocalPort = "27011";
	m_LocalIP.SetAddress(192,168,0,250);

	((CButton *)GetDlgItem(IDC_RADIO2))->SetCheck(true);

	m_C_Port.SetCurSel(0);
	m_C_Baudrate.SetCurSel(4);



	m_C_IsoTimes.SetCurSel(0);
	m_C_IsoInterval.SetCurSel(0);
	m_IsoCnt = 1;

	m_C_EpcTimes.SetCurSel(0);
	m_C_EpcInterval.SetCurSel(0);
	m_C_EpcMembank.SetCurSel(1);
	m_C_EpcWordPtr.SetCurSel(2);
	m_C_EpcWordCnt.SetCurSel(5);

	m_B_Con.EnableWindow(true);
	m_B_Discon.EnableWindow(false);

	m_SelectEPC.EnableWindow(false);
	m_SelectISO.EnableWindow(false);
	m_password = "000000";
	m_IsoData = "11223344";
	m_EpcData = "00112233445566778899AABB";

	m_C_IsoTimes.EnableWindow(false);
	m_C_IsoInterval.EnableWindow(false);
	m_E_IsoAddr.EnableWindow(false);
	m_E_IsoCnt.EnableWindow(false);
	m_E_IsoData.EnableWindow(false);
	m_B_IsoId.EnableWindow(false);
	m_B_IsoStop.EnableWindow(false);
	m_B_IsoRead.EnableWindow(false);
	m_B_IsoWrite.EnableWindow(false);
	m_B_IsoQuery.EnableWindow(false);
	m_B_IsoLock.EnableWindow(false);

	m_C_EpcTimes.EnableWindow(false);
	m_C_EpcInterval.EnableWindow(false);
	m_C_EpcMembank.EnableWindow(false);
	m_C_EpcWordPtr.EnableWindow(false);
	m_C_EpcWordCnt.EnableWindow(false);
	m_B_EpcId.EnableWindow(false);
	m_B_EpcStop.EnableWindow(false);
	m_B_EpcRead.EnableWindow(false);
	m_B_EpcWrite.EnableWindow(false);
	m_B_EpcLock.EnableWindow(false);
	m_E_EpcData.EnableWindow(false);
	m_B_EpcInit.EnableWindow(false);

	m_C_ReadAddr.AddString("广播");
	for(i = 1; i <= 240; i++)
	{
		s.Format("%d",i);
		m_C_ReadAddr.AddString(s);
	}
	for(i = 0; i<= 224; i++)
	{
		s.Format("%d",i);
		m_E_IsoAddr.AddString(s);
	}
	for(i = 1; i<= 224; i++)
	{
		s.Format("%d",i);
		m_E_IsoCnt.AddString(s);
	}
	m_E_IsoAddr.SetCurSel(8);
	m_E_IsoCnt.SetCurSel(3);
	m_C_ReadAddr.SetCurSel(0);
	
	UpdateData(false);

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CDemoDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CDemoDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CDemoDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CDemoDlg::OnCon() 
{
	// TODO: Add your control notification handler code here
	int i,br;
	BYTE v1,v2;
	CString strIP;
	int nPort;
	CString s,s1;
	BYTE ip1,ip2,ip3,ip4;

	UpdateData(true);
	i = m_C_Port.GetCurSel();
	br = m_C_Baudrate.GetCurSel();
	ReaderAddr = m_C_ReadAddr.GetCurSel();
	if(ReaderAddr == 0) 
		ReaderAddr = 0xFF;
	nPort = atoi(m_LocalPort);
	m_LocalIP.GetAddress(ip1,ip2,ip3,ip4);
	strIP.Format("%d.%d.%d.%d",ip1,ip2,ip3,ip4);
	if(1 == nTransMode) // 串口模式
	{
		if(CommOpen(hComHandle,CommPort[i]) != 0)
		{
			m_ListData.AddString("-- 打开串口失败!");
			return;
		}
		if(SetBaudRate(hComHandle,br,ReaderAddr) != 0)
		{
			m_ListData.AddString("-- 连接UHF RFID设备失败（波特率）!");
			CommClose(hComHandle);
			return;
		}
	}
	else // 网口模式
	{
		int iTimeout=0;
		for(iTimeout=0;iTimeout<3;iTimeout++)
		{
			int aStatus = NetConnect(hComHandle,strIP,nPort);
			if(aStatus == 0)
				break;
		}
		if(iTimeout>=3)
		{
			m_ListData.AddString("-- 打开网口失败!");
			return;
		}
	}
	m_ListData.AddString("-- 连接UHF RFID设备成功!");
	m_B_Con.EnableWindow(false);
	m_B_Discon.EnableWindow(true);

	m_C_IsoTimes.EnableWindow(true);
	m_C_IsoInterval.EnableWindow(true);
	m_E_IsoAddr.EnableWindow(true);
	m_E_IsoCnt.EnableWindow(true);
	m_E_IsoData.EnableWindow(true);
	m_B_IsoId.EnableWindow(true);
	m_B_IsoStop.EnableWindow(false);
	m_B_IsoRead.EnableWindow(true);
	m_B_IsoWrite.EnableWindow(true);
	m_B_IsoQuery.EnableWindow(true);
	m_B_IsoLock.EnableWindow(true);

	m_C_EpcTimes.EnableWindow(true);
	m_C_EpcInterval.EnableWindow(true);
	m_C_EpcMembank.EnableWindow(true);
	m_C_EpcWordPtr.EnableWindow(true);
	m_C_EpcWordCnt.EnableWindow(true);
	m_B_EpcId.EnableWindow(true);
	m_B_EpcStop.EnableWindow(false);
	m_B_EpcRead.EnableWindow(true);
	m_B_EpcWrite.EnableWindow(true);
	m_B_EpcLock.EnableWindow(true);
	m_E_EpcData.EnableWindow(true);
	m_B_EpcInit.EnableWindow(true);
	m_EpcKill.EnableWindow(true);

	m_SelectEPC.EnableWindow(true);
	m_SelectISO.EnableWindow(true);
	m_Setout_Btn.EnableWindow(true);

	GetFirmwareVersion (hComHandle,&v1,&v2,0xff);
	s = "-- 版本号：";
	if(v1 < 10)
	{
		s1.Format("0%d",v1);
	}
	else
		s1.Format("%d",v1);
	s += s1;
	s += ".";
	if(v2 < 10)
	{
		s1.Format("0%d",v2);
	}
	else
		s1.Format("%d",v2);
	s += s1;
	m_ListData.AddString(s);
	OnBtnQuery();
	SetBeep(hComHandle,0,0xff);// 关闭蜂鸣器
}

void CDemoDlg::OnDiscon() 
{
	// TODO: Add your control notification handler code here
	SetBeep(hComHandle,0,0xff);// 关闭蜂鸣器
	if(1 == nTransMode)
	{
		SetBaudRate(hComHandle,0,ReaderAddr);
		CommClose(hComHandle);
	}
	else
	{
		NetDisconnect(hComHandle);
	}

	m_B_Con.EnableWindow(true);
	m_B_Discon.EnableWindow(false);

	m_SelectEPC.EnableWindow(false);
	m_SelectISO.EnableWindow(false);

	m_C_IsoTimes.EnableWindow(false);
	m_C_IsoInterval.EnableWindow(false);
	m_E_IsoAddr.EnableWindow(false);
	m_E_IsoCnt.EnableWindow(false);
	m_E_IsoData.EnableWindow(false);
	m_B_IsoId.EnableWindow(false);
	m_B_IsoStop.EnableWindow(false);
	m_B_IsoRead.EnableWindow(false);
	m_B_IsoWrite.EnableWindow(false);
	m_B_IsoQuery.EnableWindow(false);
	m_B_IsoLock.EnableWindow(false);

	m_C_EpcTimes.EnableWindow(false);
	m_C_EpcInterval.EnableWindow(false);
	m_C_EpcMembank.EnableWindow(false);
	m_C_EpcWordPtr.EnableWindow(false);
	m_C_EpcWordCnt.EnableWindow(false);
	m_B_EpcId.EnableWindow(false);
	m_B_EpcStop.EnableWindow(false);
	m_B_EpcRead.EnableWindow(false);
	m_B_EpcWrite.EnableWindow(false);
	m_B_EpcLock.EnableWindow(false);
	m_E_EpcData.EnableWindow(false);
	m_B_EpcInit.EnableWindow(false);
	m_EpcKill.EnableWindow(false);
	m_Setout_Btn.EnableWindow(false);
}

void CDemoDlg::OnClose() 
{
	// TODO: Add your message handler code here and/or call default
	if(1 == nTransMode)
	{
		SetBaudRate(hComHandle,0,ReaderAddr);
		CommClose(hComHandle);
	}
	else
	{
		NetDisconnect(hComHandle);
	}
	CDialog::OnClose();
}

void CDemoDlg::OnIsoId() 
{
	// TODO: Add your control notification handler code here
	int i;
	int period[] = {10,50,100,500,1000};
	int cnt[] = {0xFFFFFFFF,1,10,100,1000,10000};
	UpdateData(true);
	i = m_C_IsoTimes.GetCurSel();
	IsoReadCnt = cnt[i];
	ClearIDBuffer(hComHandle,ReaderAddr);
	if(i == 0)				//连续识别
	{
		m_ListData.ResetContent();
		ClearIDBuffer(hComHandle,ReaderAddr);
		AddOprationInfo("6B标签识别开始!");
		MultiTagCnt = 0;
	}
	ReadSucessCnt = 0;
	int nIntev = period[m_C_EpcInterval.GetCurSel()]+rand()%period[m_C_EpcInterval.GetCurSel()];
	SetTimer(1,nIntev,NULL);
	m_B_IsoId.EnableWindow(false);
	m_B_IsoStop.EnableWindow(true);
	
}

void CDemoDlg::OnIsoStop() 
{
	// TODO: Add your control notification handler code here
	KillTimer(1);
	m_B_IsoId.EnableWindow(true);
	m_B_IsoStop.EnableWindow(false);
}

void CDemoDlg::OnTimer(UINT nIDEvent) 
{
	// TODO: Add your message handler code here and/or call default
	CString s;
	unsigned int tag_cnt = 0;
	short status;


	if(nIDEvent == 1)
	{
		if(IsoReadCnt == 0xFFFFFFFF)
		{
			status = IsoMultiTagIdentify(hComHandle,&tag_cnt,IdBuf,ReaderAddr);
			if(tag_cnt)
			{
				ReadSucessCnt++;
				DisplayTagData(tag_cnt,8,MultiTagCnt);
				MultiTagCnt += tag_cnt;
			}
		}
		else
		{
			ClearIDBuffer(hComHandle,ReaderAddr);
			IsoMultiTagIdentify(hComHandle,&tag_cnt,IdBuf,ReaderAddr);
			if(tag_cnt)
			{
				ReadSucessCnt++;
				s.Format("-- 识别标签成功 %d 次!",ReadSucessCnt);
				AddOprationInfo(s);
				DisplayTagData(tag_cnt,8,0);
			}
			if(IsoReadCnt)
				IsoReadCnt--;
			s.Format("%d",IsoReadCnt);
			m_C_IsoTimes.SetWindowText(s);
		}
		if(!IsoReadCnt)
			OnIsoStop();
	}
	else
	{
		if(EpcReadCnt == 0xFFFFFFFF)
		{
			Gen2MultiTagIdentify(hComHandle,&tag_cnt,IdBuf,ReaderAddr);
			if(tag_cnt)
			{
				ReadSucessCnt++;
				DisplayTagData(tag_cnt,12,MultiTagCnt);
				MultiTagCnt += tag_cnt;
			}
		}
		else
		{
			ClearIDBuffer(hComHandle,ReaderAddr);
			Gen2MultiTagIdentify(hComHandle,&tag_cnt,IdBuf,ReaderAddr);
			if(tag_cnt)
			{
				ReadSucessCnt++;
				s.Format("-- 识别标签成功 %d 次!",ReadSucessCnt);
				AddOprationInfo(s);
				DisplayTagData(tag_cnt,12,0);
			}
			if(EpcReadCnt)
				EpcReadCnt--;
			s.Format("%d",EpcReadCnt);
			m_C_EpcTimes.SetWindowText(s);
		}
		if(!EpcReadCnt)
			OnEpcStop();
	}
	UpdateData(false);
	CDialog::OnTimer(nIDEvent);
}



void CDemoDlg::OnClear() 
{
	// TODO: Add your control notification handler code here
	m_ListData.ResetContent();
	m_SelectEPC.ResetContent();
	m_SelectISO.ResetContent();
}

void CDemoDlg::StrToHex(unsigned char *str,unsigned char *hex,int cnt)
{
	int i,j;
	for(i = 0; i < cnt; i++)
	{
		j = i*2;
		if(str[j]>=0x41&&str[j]<=0x46)   
			hex[i] = str[j]-0x37;  
		else if(str[j]>=0x30&&str[j]<=0x39)   
			hex[i] = str[j]-0x30;  
		hex[i] <<= 4;
		j++;
		if(str[j]>=0x41&&str[j]<=0x46)   
			hex[i] += str[j]-0x37;  
		else if(str[j]>=0x30&&str[j]<=0x39)   
			hex[i] += str[j]-0x30;  
	}
}

void CDemoDlg::AddOprationInfo(CString s)
{
	int b;
	m_ListData.AddString(s);
	b=m_ListData.GetCount();   
	m_ListData.SetCurSel(b-1);   
}

void CDemoDlg::DisplayTagData(int cnt,int tag_len,int start_index)
{
	CString s,s0,tmpCode;
	int i,j,Disp_len=0;
	unsigned char t;
	for(i = 0; i < cnt; i++)
	{
		s.Format("NO.%d: ",start_index+i+1);
		tmpCode="";
		if(tag_len == 8) // 6B Tag
			Disp_len = 8;
		else
		{
			Disp_len = 12;//(IdBuf[i].Ids[0] >> 3) * 2 + 2;
		}
		for(j = 0; j < Disp_len; j++)
		{
			t = IdBuf[i].Ids[j];
			if(t < 0x10)
			{
				s0.Format("0%X",t);
			}
			else
				s0.Format("%X",t);
			s += s0;
			tmpCode += s0;
		}
		CTime systemtime=CTime::GetCurrentTime();   
		CString strAntTime="";
		strAntTime.Format(", %d, %d-%d-%d %d:%d:%d",(IdBuf[i].AntNum+1),systemtime.GetYear(),systemtime.GetMonth(),systemtime.GetDay(),systemtime.GetHour(),systemtime.GetMinute(),systemtime.GetSecond());
		
		AddOprationInfo(s+strAntTime);
	}
}

void CDemoDlg::OnChangePower() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	UpdateData(true);
}

void CDemoDlg::OnIsoRead() 
{
	// TODO: Add your control notification handler code here
	unsigned char addr,antNum;
	short status;
	unsigned char i,j,k=0;
	unsigned char buf[256];
	CString s,s0;
	UpdateData(true);
	m_IsoAddr = m_E_IsoAddr.GetCurSel();
	m_IsoCnt = m_E_IsoCnt.GetCurSel()+1;
	addr = m_IsoAddr;
	for(i = 0; i < m_IsoCnt;)
	{
		if(m_Check6B)
		{
			char *buf_s;
			unsigned char buf_iso[8];
			CString strISO="";
			GetDlgItemText(COMBO_6B_SELECT,strISO);
			buf_s = strISO.GetBuffer(16);
			StrToHex((unsigned char *)buf_s,buf_iso,8);
			status = IsoReadWithID(hComHandle,buf_iso,addr+i,&antNum,buf+k,ReaderAddr);
		}
		else
			status = IsoSigleTagRead(hComHandle,addr+i,buf+k,ReaderAddr);
		if(status)
		{
			j++;
			if(j == 3)
			{
				AddOprationInfo("--读取6B标签数据失败!");
				return;
			}
		}
		else
		{
			j = 0; 
			i += 8;
			// 不指定ID读取时返回第一个字节是天线号共返回9字节数据，指定ID只返回8字节数据
			if(m_Check6B)
				k += 8;
			else
				k += 9;
		}			
	}
	AddOprationInfo("--读取6B标签数据成功, 数据＝");
	s="";
	if(m_Check6B)
	{
		for(i = 0; i < m_IsoCnt;i++)
		{
			s0.Format("%02X ",buf[i]);
			s += s0;
		}
		AddOprationInfo(s);
	}
	else
	{
		for(i = 0; i < (m_IsoCnt+(m_IsoCnt/9+1));i++)
		{
			if((i % 9)==0)
				continue;
			s0.Format("%02X ",buf[i]);
			s += s0;
		}
		AddOprationInfo(s);
	}
	UpdateData(false);
}

void CDemoDlg::OnChangeIsoAddr() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	UpdateData(true);
}

void CDemoDlg::OnChangeIsoCnt() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	UpdateData(true);
}

void CDemoDlg::OnIsoWrite() 
{
	// TODO: Add your control notification handler code here
	unsigned char addr;
	unsigned char i,j;
	short status=0;
	char *buf_s;
	unsigned char buf_h[20];
	CString s,s0;
	UpdateData(true);
	m_IsoAddr = m_E_IsoAddr.GetCurSel();
	m_IsoCnt = m_E_IsoCnt.GetCurSel()+1;

	addr = m_IsoAddr;
	if(m_IsoCnt > 10)
	{
		AddOprationInfo("请不要一次输入大于10字节数据!");
		return;
	}
	i = m_IsoData.GetLength();
	if(i < m_IsoCnt*2)
	{
		AddOprationInfo("--输入数据长度不足!");
		return;
	}
	buf_s = m_IsoData.GetBuffer(m_IsoCnt*2);
	StrToHex((unsigned char *)buf_s,buf_h,m_IsoCnt);
	for(i = 0; i < m_IsoCnt;)
	{
		if(m_Check6B)
		{
			char *buf_s;
			unsigned char buf_iso[8];
			CString strISO="";
			GetDlgItemText(COMBO_6B_SELECT,strISO);
			buf_s = strISO.GetBuffer(16);
			StrToHex((unsigned char *)buf_s,buf_iso,8);
			status = IsoWriteWithID(hComHandle,buf_iso,addr+i,buf_h[i],ReaderAddr);
		}
		else
			status = IsoWriteTag(hComHandle,addr+i,buf_h[i],ReaderAddr);
		if(status == 0)
		{
			i++;
			j = 0;
		}
		else
		{
			j++;
			if(j > 3)
			{
				AddOprationInfo("--写6B标签失败!");
				return;
			}
		}
		Sleep(200);
	}
	AddOprationInfo("--写6B标签成功!");
}

void CDemoDlg::OnIsoLock() 
{
	// TODO: Add your control notification handler code here
	unsigned int i,j;
	short status;

	UpdateData(true);
	m_IsoAddr = m_E_IsoAddr.GetCurSel();
	m_IsoCnt = m_E_IsoCnt.GetCurSel()+1;

	for(i = 0; i < m_IsoCnt;)
	{
		status = IsoLockTag(hComHandle,m_IsoAddr+i,ReaderAddr);
		if(status == 0)
		{
			i++;
			j = 0;
		}
		else
		{
			j++;
			if(j > 3)
			{
				AddOprationInfo("--锁定6B标签指定单元失败!");
				return;
			}
		}
		Sleep(200);
	}
	AddOprationInfo("--锁定6B标签指定单元成功!");
}	


void CDemoDlg::OnIsoQuery() 
{
	// TODO: Add your control notification handler code here
	unsigned int i,j;
	short status;
	unsigned char lock[40];
	CString s;

	UpdateData(true);
	m_IsoAddr = m_E_IsoAddr.GetCurSel();
	m_IsoCnt = m_E_IsoCnt.GetCurSel()+1;

	for(i = 0; i < m_IsoCnt;)
	{
		status = IsoQueryLock(hComHandle,m_IsoAddr+i,lock+i,ReaderAddr);
		if(status == 0)
		{
			i++;
			j = 0;
		}
		else
		{
			j++;
			if(j > 3)
			{
				AddOprationInfo("--查询6B标签锁定指定单元状态失败!");
				return;
			}
		}
		Sleep(20);
	}
	AddOprationInfo("--查询6B标签锁定指定单元状态成功!");
	for(i = 0; i < m_IsoCnt; i++)
	{
		s.Format("地址 %d 状态： ",m_IsoAddr+i);
		if(lock[i])
			s+="已锁!";
		else
			s+="未锁!";
		AddOprationInfo(s);
	}
}

void CDemoDlg::OnEpcId() 
{
	// TODO: Add your control notification handler code here
	// TODO: Add your control notification handler code here
	int i;
	int period[] = {10,50,100,500,1000};
	int cnt[] = {0xFFFFFFFF,1,10,100,1000,10000};
	UpdateData(true);
	i = m_C_EpcTimes.GetCurSel();
	EpcReadCnt = cnt[i];
	if(i == 0)				//连续识别
	{
		m_ListData.ResetContent();
		ClearIDBuffer(hComHandle,ReaderAddr);
		AddOprationInfo("EPC标签识别开始!");
		MultiTagCnt = 0;
	}
	ReadSucessCnt = 0;
	int nIntev = period[m_C_EpcInterval.GetCurSel()]+rand()%period[m_C_EpcInterval.GetCurSel()];
	SetTimer(2,nIntev,NULL);
	m_B_EpcId.EnableWindow(false);
	m_B_EpcStop.EnableWindow(true);	
}

void CDemoDlg::OnEpcStop() 
{
	// TODO: Add your control notification handler code here
	KillTimer(2);
	m_B_EpcId.EnableWindow(true);
	m_B_EpcStop.EnableWindow(false);	
}

void CDemoDlg::OnEpcRead() 
{
	// TODO: Add your control notification handler code here
	int i;
	unsigned char MemBank,WordCnt,WordPtr;
	unsigned char buf[256];
	short status;
	CString s,s0;

	UpdateData(true);

	MemBank = m_C_EpcMembank.GetCurSel();
	WordCnt = m_C_EpcWordCnt.GetCurSel()+1;
	WordPtr = m_C_EpcWordPtr.GetCurSel();

	status = Gen2Read(hComHandle,MemBank,WordPtr,WordCnt,buf,ReaderAddr);
	if(status)
	{
		AddOprationInfo("--读取EPC标签数据失败!");
		return;
	}
	else
	{
		AddOprationInfo("--读取EPC标签数据成功,数据＝");
		for(i = 1; i < WordCnt*2+1;)
		{
			if(buf[i] < 0x10)
			{
					s0.Format("0%X ",buf[i]);
			}
			else
				s0.Format("%X ",buf[i]);
			s += s0;
			i++;
			if((i % 14) == 0)
			{
				AddOprationInfo(s);
				s = "";
			}
		}
	}
	AddOprationInfo(s);
	UpdateData(false);
}

void CDemoDlg::OnInit() 
{
	// TODO: Add your control notification handler code here
	short status;

	status = Gen2InitEPC(hComHandle,6,ReaderAddr);
	if(!status)
	{
		AddOprationInfo("--初始化EPC标签数据长度成功（标准96Bit）!");
	}
	else
		AddOprationInfo("--初始化EPC标签数据长度失败!");
}

void CDemoDlg::OnEpcWrite() 
{
	// TODO: Add your control notification handler code here
	unsigned char MemBank,WordCnt,WordPtr;
	unsigned char i=0,j=0;
	short status=0;
	char *buf_s;
	unsigned char buf_h[256];
	unsigned char buf_epc[12];
	unsigned short temp;
	CString s,s0;

	UpdateData(true);
	MemBank = m_C_EpcMembank.GetCurSel();
	WordCnt = m_C_EpcWordCnt.GetCurSel()+1;
	WordPtr = m_C_EpcWordPtr.GetCurSel();

	i = m_EpcData.GetLength();
	if(i < WordCnt*4)
	{
		AddOprationInfo("--输入数据长度不足!");
		return;
	}
	buf_s = m_EpcData.GetBuffer(WordCnt*4);
	StrToHex((unsigned char *)buf_s,buf_h,WordCnt*2);

	if(m_CheckEPC)
	{
		CString strEPC="";
		GetDlgItemText(COMBO_EPC_SELECT,strEPC);
		buf_s = strEPC.GetBuffer(24);
		StrToHex((unsigned char *)buf_s,buf_epc,12);
	}

	for(i = 0; i < WordCnt;)
	{
		temp = buf_h[i*2]<<8;
		temp += buf_h[i*2+1];

		while(j<=3)
		{
			status = Gen2Write(hComHandle,MemBank,WordPtr,temp,ReaderAddr);
			if(status == 0)
			{
				i++;
				j = 0;
				WordPtr++;
			}
			else
			{
				j++;
				if(j > 3)
				{
					AddOprationInfo("--写EPC标签失败!");
					return;
				}
			}
			Sleep(200);
		}
	}
	AddOprationInfo("--写EPC标签成功!");	
}

void CDemoDlg::OnEpcLock() 
{
	// TODO: Add your control notification handler code here
	short status;
	unsigned char MemBank = m_C_EpcMembank.GetCurSel();
	status = Gen2LockTag(hComHandle,MemBank,ReaderAddr);
	if(status == 0)
	{
		AddOprationInfo("--锁定EPC标签成功!");
	}
	else
	{
		AddOprationInfo("--锁定EPC标签失败!");
	}

}

void CDemoDlg::OnEpcKill() 
{
	// TODO: Add your control notification handler code here
	short status;
	UpdateData(true);
	unsigned int password;// = strtoul(m_password,NULL,8);
	sscanf(m_password,"%8x",&password);   
	status = Gen2KillTag(hComHandle ,password, ReaderAddr);
	if(status == 0)
	{
		AddOprationInfo("销毁EPC标签成功!");
	}
	else
	{
		AddOprationInfo("销毁EPC标签失败!");
	}	
}

LRESULT CAboutDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) 
{
	// TODO: Add your specialized code here and/or call the base class
	
	return CDialog::WindowProc(message, wParam, lParam);
}

void CDemoDlg::OnSavelog() 
{
	int nListCnt = m_ListData.GetCount();
	if(nListCnt>0)
	{
		CString strLogMsg,strList;
		strLogMsg = "";
		for(int i=0; i<nListCnt; i++)
		{
			m_ListData.GetText(i,strList);
			if(strList.Left(3) == "NO.")
			{
				int nPos = strList.Find(":",3);
				strLogMsg = strLogMsg + strList.Mid(nPos+1) +"\r\n";
			}
		}
		WriteLogFile(strLogMsg);
	}		
}

int CDemoDlg::WriteLogFile(CString logmsg)
{
	UpdateData();
	CFile file;
	CString strFileName;
	CString strTitle="                               标签EPC码       ,天线号,      时间\r\n";
	try
	{
		CTime systemtime=CTime::GetCurrentTime();   
		strFileName.Format(".\\Data%d%d%d%d%d%d.txt",systemtime.GetYear(),systemtime.GetMonth(),systemtime.GetDay(),systemtime.GetHour(),systemtime.GetMinute(),systemtime.GetSecond());
		if(!file.Open(strFileName,CFile::modeReadWrite))     
		{     
			file.Open(strFileName,CFile::modeCreate|CFile::modeReadWrite);     
		}   
		file.SeekToEnd();   
		char* writechar;
		writechar=(LPTSTR)(LPCTSTR)strTitle;
		file.Write(writechar,lstrlen(writechar));   

		writechar=(LPTSTR)(LPCTSTR)logmsg;
		file.Write(writechar,lstrlen(writechar));   
		file.Close();
	}
	catch(...)
	{
		MessageBox("保存数据文件【" + strFileName.Mid(2) +"】失败");
		return -1;
	}
	MessageBox("保存数据文件【" + strFileName.Mid(2) +"】成功");
	return 0;
} 

void CDemoDlg::OnRadio1() 
{
	((CButton *)GetDlgItem(IDC_RADIO2))->SetCheck(FALSE);
	nTransMode = 0;

	GetDlgItem(IDC_STATIC_COMMPORT)->ShowWindow(false);
	GetDlgItem(COMBO_PORT)->ShowWindow(false);
	GetDlgItem(IDC_STATIC_BAUDRATE)->ShowWindow(false);
	GetDlgItem(COMBO_BAUDRATE)->ShowWindow(false);
	GetDlgItem(IDC_STATIC_ADDRCODE)->ShowWindow(false);
	GetDlgItem(COMBO__READER_ADDR)->ShowWindow(false);

	GetDlgItem(IDC_STATIC_IP)->ShowWindow(true);
	GetDlgItem(IDC_IP)->ShowWindow(true);
	GetDlgItem(IDC_STATIC_NETPORT)->ShowWindow(true);
	GetDlgItem(IDC_PORT)->ShowWindow(true);	
}

void CDemoDlg::OnRadio2() 
{
	((CButton *)GetDlgItem(IDC_RADIO1))->SetCheck(false);
	nTransMode = 1;	

	GetDlgItem(IDC_STATIC_IP)->ShowWindow(false);
	GetDlgItem(IDC_IP)->ShowWindow(false);
	GetDlgItem(IDC_STATIC_NETPORT)->ShowWindow(false);
	GetDlgItem(IDC_PORT)->ShowWindow(false);


	GetDlgItem(IDC_STATIC_COMMPORT)->ShowWindow(true);
	GetDlgItem(COMBO_PORT)->ShowWindow(true);
	GetDlgItem(IDC_STATIC_BAUDRATE)->ShowWindow(true);
	GetDlgItem(COMBO_BAUDRATE)->ShowWindow(true);
	GetDlgItem(IDC_STATIC_ADDRCODE)->ShowWindow(true);
	GetDlgItem(COMBO__READER_ADDR)->ShowWindow(true);
}

void CDemoDlg::OnBtnQuery() 
{
	BYTE	iPower=0,iStep=0;

	if(GetRf(hComHandle,&iPower,&iStep,ReaderAddr) != 0)
	{
		AddOprationInfo("查询参数失败");
		return;
	}
	AddOprationInfo("查询参数成功");
	m_PowerSet.SetCurSel(iPower);
	m_Freq.SetCurSel(iStep);
}

void CDemoDlg::OnBtnSetting() 
{
	BYTE	iPower=0,iStep=0;
	iPower=m_PowerSet.GetCurSel();
	iStep=m_Freq.GetCurSel();

	if(SetRf(hComHandle,iPower,iStep,ReaderAddr) != 0)
	{
		AddOprationInfo("设置参数失败");
		return;
	}
	AddOprationInfo("设置参数成功");
}

void CDemoDlg::OnBtnSetout() 
{
	int ChkValue[4];
	ChkValue[0] = ((CButton *)GetDlgItem(IDC_CHECK_OUT1))->GetCheck();
	ChkValue[1] = ((CButton *)GetDlgItem(IDC_CHECK_OUT2))->GetCheck();
	ChkValue[2] = ((CButton *)GetDlgItem(IDC_CHECK_OUT3))->GetCheck();
	ChkValue[3] = ((CButton *)GetDlgItem(IDC_CHECK_OUT4))->GetCheck();
	BYTE SetValue=(BYTE)(ChkValue[3]*8 + ChkValue[2]*4 + ChkValue[1]*2 + ChkValue[0]);

	if(SetOutput(hComHandle,SetValue,ReaderAddr) != 0)
	{
		AddOprationInfo("设置输出失败");
		return;
	}
	AddOprationInfo("设置输出成功");
	int isBeepOn;
	isBeepOn = ((CButton *)GetDlgItem(IDC_CHECK_BEEP))->GetCheck();
	if(SetBeep(hComHandle,(BYTE)isBeepOn,ReaderAddr) != 0)
	{
		AddOprationInfo("设置蜂鸣器失败");
		return;
	}
	AddOprationInfo("设置蜂鸣器成功");
}

void CDemoDlg::OnBtnReset() 
{
	// TODO: Add your control notification handler code here
	ResetReader(hComHandle,0xff);
	OnDiscon();
}

void CDemoDlg::OnEpcFastwrite() 
{
	// TODO: Add your control notification handler code here
	unsigned char MemBank,WordCnt,WordPtr;
	unsigned char i=0,j=0;
	short status=0;
	char *buf_s;
	unsigned char buf_h[256];
	unsigned char buf_epc[12];
	unsigned short temp;
	CString s,s0;

	UpdateData(true);
	MemBank = m_C_EpcMembank.GetCurSel();
	WordCnt = m_C_EpcWordCnt.GetCurSel()+1;
	WordPtr = m_C_EpcWordPtr.GetCurSel();

	i = m_EpcData.GetLength();
	if(i < WordCnt*4)
	{
		AddOprationInfo("--输入数据长度不足!");
		return;
	}
	buf_s = m_EpcData.GetBuffer(WordCnt*4);
	StrToHex((unsigned char *)buf_s,buf_h,WordCnt*2);

	if(m_CheckEPC)
	{
		CString strEPC="";
		GetDlgItemText(COMBO_EPC_SELECT,strEPC);
		buf_s = strEPC.GetBuffer(24);
		StrToHex((unsigned char *)buf_s,buf_epc,12);
	}

	for(i = 0; i < 3;)
	{
		temp = buf_h[i*2]<<8;
		temp += buf_h[i*2+1];

		status = Gen2FastWrite(hComHandle,MemBank,WordPtr,WordCnt,buf_h,ReaderAddr);
		if(status == 0)
		{
			i=5;
			j=0;
			break;
		}
		else
		{
			j++;
			if(j > 3)
			{
				AddOprationInfo("--写EPC标签失败!");
				return;
			}
		}
		Sleep(200);
	}
	AddOprationInfo("--写EPC标签成功!");
}

void CDemoDlg::OnBtnGetant() 
{
	// TODO: Add your control notification handler code here
	int aStatus;
	BYTE byAntenna = 0;
	aStatus = GetAnt(hComHandle,&byAntenna,ReaderAddr);

	if(aStatus == 0)
	{
		AddOprationInfo("--查询天线端口设置成功!");
	}
	else
	{
		AddOprationInfo("--查询天线端口设置失败!");
		return;
	}

	m_Ant1=byAntenna & 0x01;
	m_Ant2=byAntenna & 0x02;
	m_Ant3=byAntenna & 0x04;
	m_Ant4=byAntenna & 0x08;
	UpdateData(false);	
}

void CDemoDlg::OnBtnSetant() 
{
	// TODO: Add your control notification handler code here
	int aStatus;
	BYTE byAntenna = 0;

	UpdateData(true);
	if(m_Ant1) byAntenna |= 0x01;
	if(m_Ant2) byAntenna |= 0x02;
	if(m_Ant3) byAntenna |= 0x04;
	if(m_Ant4) byAntenna |= 0x08;

	aStatus = SetAnt(hComHandle,byAntenna,ReaderAddr);
	if(aStatus == 0)
	{
		AddOprationInfo("天线端口设置成功!");
	}
	else
	{
		AddOprationInfo("天线端口设置失败!");		
	}
}
